import React, { ReactNode } from 'react';
import { Button, Form, Icon, Upload } from 'antd';
import BraftEditor from "braft-editor";
import * as DataHelper from "@/helpers/DataHelper";
import { ContentUtils } from 'braft-utils';
import * as BdHelper from "@/utils/BdHelper";

const FormItem = Form.Item;

interface PropsType {
  label?: string | ReactNode;
  name: string;
  initialValue?: any;
  itemLayout?: {};
  rules?: any;
  form: any;
}
const InputItem: React.FC<PropsType> = props => {
  const {
    label,
    name,
    initialValue,
    // 不定义默认值，否则在form中定义后，form中的itemLayout不生效，此处会把form中的覆盖掉
    // 此处在form中统一处理，如果需要覆盖则在引用此组件处进行定义
    // itemLayout={
    //   labelCol: { span: 4 },
    //   wrapperCol: { span: 14 },
    // },
    itemLayout = {},
    rules,
    form,
  } = props;

  const token = BdHelper.getBdToken();

  return (
    <FormItem label={label} {...itemLayout}>
      {form.getFieldDecorator(name, {
        initialValue,
        rules,
      })(<BraftEditor style={{ border: '1px solid #ccc' }} controls={[
        ...BraftEditor.defaultProps.controls,
        {
          key: 'antd-uploader',
          type: 'component',
          component: (
            <Upload
              accept="image/*"
              action="/api/admin/file/upload"
              showUploadList={false}
              data={{ type: 'image' }}
              headers={{
                Authorization: `Bearer ${token}`,
              }}
              onChange={res => {
                if (res.file.status == 'done') {
                  console.log('res', res);
                  const fileArr = DataHelper.getLastUploadFile(res.fileList);
                  if (fileArr.length > 0) {
                    form.setFieldsValue({
                      content: ContentUtils.insertMedias(form.getFieldValue(name), [{
                        type: 'IMAGE',
                        url: fileArr[0].file_url,
                      }])
                    });
                  }
                }
              }}
            >
              <Button className="control-item button upload-button" data-title="插入图片">
                <Icon type="picture" theme="filled" />
              </Button>
            </Upload>
          )
        }
      ]} />)}
    </FormItem>

  );
};
export default InputItem;
